﻿#include <iostream>
#include <vector>
using namespace std;

class Flyweight
{
public:
	Flyweight(string & state)
	{
		m_State = state;
	}

	virtual ~Flyweight(){}

	string& GetState()
	{
		return m_State;
	}

	virtual void Operation() = 0;

protected:
	string m_State;
};

class ConcreteFlyweight : public Flyweight
{
public:
	virtual ~ConcreteFlyweight()
	{
		cout << "release Concrete Flyweight :" << GetState() << endl;
	}
	ConcreteFlyweight(string& state) : Flyweight(state)
	{
		cout << "ConcreteFlyweight init" << endl;
	}

	void Operation()
	{
		cout << "ConcreteFlyweight:" << GetState() << endl;
	}
};

class FlyweightFactory
{
public:
	FlyweightFactory()
	{
		m_vecFlyWeight.clear();
	}

	virtual ~FlyweightFactory()
	{
		for (auto fly : m_vecFlyWeight)
		{
			delete fly;
		}
		m_vecFlyWeight.clear();
	}

	Flyweight* GetFlyweight(string state)
	{
		for (auto fly : m_vecFlyWeight)
		{
			if (fly->GetState() == state)
			{
				cout << " state " << state << "has been create" << endl;
				return fly;
			}
		}

		auto fly = new ConcreteFlyweight(state);
		m_vecFlyWeight.push_back(fly);
		return fly;
	}
private:
	vector<Flyweight*> m_vecFlyWeight;
};
int main()
{
	FlyweightFactory* factory = new FlyweightFactory();
	factory->GetFlyweight("hello");
	factory->GetFlyweight("world");
	factory->GetFlyweight("hello");

	delete factory;
	return 0;
}
